package org.travel.app.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.travel.app.entity.BaseReservation;
import org.travel.app.entity.Order;
import org.travel.app.entity.user.UserDiscountTicket;
import org.travel.app.entity.ticket.TicketDiscount;

import java.sql.Timestamp;

/**
 * @author nmm
 * @date 2024-12-2024/12/11
 * @deriction 用于初始化订单
 */
@Component
public  class InitOrder  {

    /**
     * 订单号生成
     */
    @Autowired
    private  OrderNumberGenerator orderNumberGenerator;

    /**
     * 创建预约订单信息
     * @param reservation
     * @return
     */
    public  Order createOrder(BaseReservation reservation) {
        // 创建 Order 对象
        Order order=new Order();
        String orderNumber = orderNumberGenerator.generateOrderNumber();
        //生成订单编号

        //设置订单编号
        order.setOrderId(orderNumber);
        if (reservation.getCouponDetail()!=null){
            order.setDiscountId(reservation.getCouponDetail().getDiscountId());
        }
        order.setReservationId(reservation.getReservationId());
        //将订单和预约信息绑定

        order.setReservationId(reservation.getReservationId());
        //绑定预约编号

        //下单时间
        order.setOrderTime(new Timestamp(System.currentTimeMillis()));

        order.setTotalPrice(reservation.getTotalPrice());
        // 设置总价(预约总价)

        order.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        //设置订单创建时间

        order.setStatus(1);
        // 设置为1 表示默认为未支付

        if (initUseDiscountTicket(reservation)!=null){
            order.setUserDiscountTicket(initUseDiscountTicket(reservation));
        }
        //设置用户优惠券使用信息

        return order;
    }

    /**
     *  初始化用户优惠券信息(如果用户使用了优惠券用于对优惠券数量进行减少操作)
     * @param reservation
     * @return
     */
    public UserDiscountTicket initUseDiscountTicket(BaseReservation reservation) {
        UserDiscountTicket userDiscountTicket=null;
        //如果优惠信息不为空
        if (reservation.getCouponDetail()!=null){
            UserDiscountTicket userDiscountTickets=new UserDiscountTicket();
            userDiscountTickets.setUserId(reservation.getUserId());
            //创建用户优惠券交易信息
            userDiscountTickets.setQuantity(reservation.getCouponDetail().getTicketQuantity());
            //设置优惠券使用数量(默认一张)
            TicketDiscount ticketDiscount=new TicketDiscount();
            ticketDiscount.setDiscountId(reservation.getCouponDetail().getDiscountId());
            userDiscountTickets.setTicketDiscount(ticketDiscount);
            userDiscountTickets.setUserId(reservation.getUserId());
            //设置用户id，用于提供给addUserPoint方法给用户随机添加积分(使用优惠消费)
            userDiscountTicket=userDiscountTickets;
        }
        return userDiscountTicket;
    }

}